package com.lntea.jdbc.dbcp;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDataSource;
import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.BeanProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.impl.GenericObjectPool;

import com.lntea.jdbc.dbutils.User;

public class PoolingDataSourceDemo {
	static DataSource getDataSource(){
		//创建connection工厂
		ConnectionFactory factory = 
				new DriverManagerConnectionFactory("jdbc:mysql://localhost:3306/jfinalweb", "root", "root");
		//连接池
		ObjectPool pool = new GenericObjectPool();
		//池化connection工厂
		//PoolableConnectionFactory(ConnectionFactory connFactory, ObjectPool pool, 
		//KeyedObjectPoolFactory stmtPoolFactory, String validationQuery, boolean defaultReadOnly, 
		//boolean defaultAutoCommit)
		PoolableConnectionFactory poolableConnectionFactory = 
				new PoolableConnectionFactory(factory, pool,null,null,false,true);
		//创建DataSource
		PoolingDataSource poolingDataSource = new PoolingDataSource(pool);
		
		return poolingDataSource;
	}
	
	public static void main(String[] args) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("password_salt", "passwordSalt");
		BeanProcessor customBeanProcessor = new BeanProcessor(map);
		ResultSetHandler<List<User>> h = new BeanListHandler<User>(User.class,new BasicRowProcessor(customBeanProcessor));

		QueryRunner queryRunner = new QueryRunner(getDataSource());
		List<User> users = null;
		try {
			users = queryRunner.query("select * from users", h);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		for (User user : users)
			System.out.println(user);
	}
}
